#!/usr/bin/env python3

import os
import sys
from stock import Stock

def show_prob_N_M(stPaths, N=5, M=1, min_samples=100):
    """
    Show probability of making money if buying in when pC > pN (average N-day price) for M days.
    """
    def generate_profit_list(Ps, As, m):
        profits = []
        assert(len(Ps) == len(As))
        for idx in range(m-1, len(Ps)-1):
            pricesM = Ps[idx-m+1:idx+1]
            pO_next, pH_next, pL_next, pC_next = Ps[idx+1]
            average = As[idx]
            satisfy = True
            for i in range(0, m):
                if pricesM[i][3] <= average:
                    satisfy = False
                    break
            if satisfy:
                profits.append(pC_next-pricesM[-1][3])
        return profits

    stocks = []
    probs = []
    for stpath in stPaths:
        stock = Stock(fromfile=stpath)
        stocks.append(stock)
    for st in stocks:
        prices = st.getPrices()
        averageNs = st.getAverages(N)
        profits = generate_profit_list(prices, averageNs, M)
        totalN = len(profits)
        if totalN < min_samples:
            #print("%s not having enough days upon 5day average price" % st.getCode())
            probs.append(-1)
            continue
        profits_positive = [p for p in profits if p > 0]
        positiveN = len(profits_positive)
        prob = float(positiveN/totalN)
        probs.append(prob)
        #print("%s: %s" % (st.getCode(), prob))
    for idx in range(0, len(stocks)):
        if probs[idx] >= 0:
            print("%s: %s" % (stocks[idx].getCode(), probs[idx]))
    valid_probs = [p for p in probs if p>=0]
    average_prob = sum(valid_probs)/len(valid_probs)
    print("average: %s" % average_prob)


if __name__ == '__main__':
    show_prob_N_M(sys.argv[1:], N=5, M=1)
